#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>

int main()
{
  //[root@localhost myshell]#
  char cmd_line[1024];
  char* g_argv[64] = {0};
  while(1)
  {
     printf("[root@localhost myshell]# ");
     fflush(stdout);
     memset(cmd_line, 0, sizeof(cmd_line));
     if(fgets(cmd_line, sizeof cmd_line, stdin) == NULL)
       break;

     // ls -a -l\n
     //去掉\n
     cmd_line[strlen(cmd_line)-1] = '\0';

     // 解析命令
     g_argv[0] = strtok(cmd_line, " ");
     int i = 0;
     if(strcmp(g_argv[0], "ll") == 0)
     {
       g_argv[0] = "ls";
       g_argv[++i] = "-l";
     }
     if(strcmp(g_argv[0], "ls") == 0)
       g_argv[++i] = "--color=auto";
     while(g_argv[i++])
     {
        g_argv[i] = strtok(NULL, " ");
     }


    // int j = 0;
    // for(j = 0; j < i; j++)
    // {
    //   if(g_argv[j] != NULL)
    //    printf("%s\n", g_argv[j]);
    //   else 
    //     printf("NULL\n");
    // }
   
    // 内置命令
    if(strcmp(g_argv[0], "cd") == 0)
    {
      if(g_argv[1])
        chdir(g_argv[1]);
      continue;
    }

   //fork
   pid_t id = fork();
   if(id == 0)
   {
     //子进程
     printf("子进程执行以下代码\n");
     execvp(g_argv[0], g_argv);
     exit(1);
   }
   else 
   {
     //父进程
     printf("这是父进程\n");
     int status = 0;
     int ret = waitpid(-1, &status, 0);
     if(ret > 0) 
        printf("wait success, exit code: %d\n", WEXITSTATUS(status));
    
   }
    
  }
  return 0;
}
